export const commonStatus = {
	info: -3,//默认，未申请
	ing: -1,//已申请，审批中
	success: 0,//申请通过
	fail: 1,//未通过
}

export const pickerOptions = {
	shortcuts: [{
		text: '今天',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			picker.$emit('pick', [start, end]);
		}
	}, {
		text: '最近一周',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			picker.$emit('pick', [start, end]);
		}
	}, {
		text: '最近一个月',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			picker.$emit('pick', [start, end]);
		}
	}, {
		text: '最近三个月',
		onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			picker.$emit('pick', [start, end]);
		}
	}]
}

export function format(timestamp, format = "yyyy-MM-dd hh:mm:ss") {
	/* 判断是否为毫秒 */
	timestamp = Number(timestamp.toString().padEnd(13, 0));
	const date = new Date(timestamp);
	/* 格式年份 */
	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
	};
	/* 其他事件正则 */
	let o = {
		'M+': date.getMonth() + 1,
		'd+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	};
	for (let k in o) {
		if (new RegExp(`(${k})`).test(format)) {
			let str = o[k] + '';
			format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? str : str.padStart(2, 0));
		}
	}
	return format;
}
//多少时间前
export function formatDistanceTime(timestamp, format = "dd天hh时mm分钟") {
	let allS = parseInt(timestamp / 1000);
	let h, m, s, d, M, y;
	if (allS > 60) {
		m = parseInt(allS / 60);
		s = parseInt(allS % 60);
		if (m > 60 && format.indexOf("h") != -1) {
			h = parseInt(m / 60);
			m = parseInt(m % 60);
			if (h > 24 && format.indexOf("d") != -1) {
				d = parseInt(h / 24);
				h = parseInt(h % 24);
			}
		}
	} else {
		s = allS;
	}
	let o = {
		"h+": h || 0,
		"m+": m || 0,
		"s+": s || 0,
		"d+": d || 0,
	};
	for (let k in o) {
		if (new RegExp(`(${k})`).test(format)) {
			let str = o[k] + "";
			format = format.replace(
				RegExp.$1,
				RegExp.$1.length === 1 ? str : str.padStart(2, 0)
			);
		}
	}
	return format;
}

//获取当前时间点的日期数据
export function getCurrentTime(date = null) {
	date = date ? new Date(date) : new Date();
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var monthFormat = month.toString().padStart(2, 0)
	var day = date.getDate();
	var dayFormat = day.toString().padStart(2, 0)
	var hour = date.getHours();
	var hourFormat = hour.toString().padStart(2, 0)
	var minute = date.getMinutes();
	var minuteFormat = minute.toString().padStart(2, 0)
	var second = date.getSeconds();
	var secondFormat = second.toString().padStart(2, 0)
	var week;
	var d = date.getDay()
	switch (d) {
		case 0:
			week = '日';
			break;
		case 1:
			week = '一';
			break;
		case 2:
			week = '二';
			break;
		case 3:
			week = '三';
			break;
		case 4:
			week = '四';
			break;
		case 5:
			week = '五';
			break;
		case 6:
			week = '六';
			break;
	}
	return {
		year: year,
		month: month,
		monthFormat: monthFormat,
		day: day,
		dayFormat: dayFormat,
		hour: hour,
		hourFormat: hourFormat,
		minute: minute,
		minuteFormat: minuteFormat,
		second: second,
		secondFormat: secondFormat,
		week: week
	}
}

/**
 *获取下几个月的输入日期
 *{param:DateTime} date 输入日期(YYYY-MM-DD)
 *{param:number } monthNum 月数
 */
export function getNextMonthDay(date, monthNum = 1) {
	var dateArr = date.split('-');
	var year = dateArr[0]; //获取当前日期的年份
	var month = dateArr[1]; //获取当前日期的月份
	var day = dateArr[2]; //获取当前日期的日
	var days = new Date(year, month, 0).getDate();//获取当前日期中的月的天数
	var year2 = year;
	var month2 = parseInt(month) + parseInt(monthNum);
	if (month2 > 12) {
		year2 = parseInt(year2) + parseInt((parseInt(month2) / 12 == 0 ? 1 : parseInt(month2) / 12));
		month2 = parseInt(month2) % 12;
	}
	var day2 = day;
	var days2 = new Date(year2, month2, 0).getDate();
	if (day2 > days2) {
		day2 = days2;
	}
	month2 = month2.toString().padStart(2, 0)

	var t2 = year2 + '-' + month2 + '-' + day2;
	return t2;
}

/**
 *获取几个月前的输入日期
 *{param:DateTime} date 输入日期(YYYY-MM-DD)
 *{param:number } monthNum 月数
 */
export function getPreMonthDay(date, monthNum = 1) {
	var dateArr = date.split('-');
	var year = dateArr[0]; //获取当前日期的年份
	var month = dateArr[1]; //获取当前日期的月份
	var day = dateArr[2]; //获取当前日期的日
	var days = new Date(year, month, 0).getDate();//获取当前日期中的月的天数
	var year2 = year;
	var month2 = parseInt(month) - monthNum;
	if (month2 <= 0) {
		year2 = parseInt(year2) - parseInt(month2 / 12 == 0 ? 1 : parseInt(month2) / 12);
		month2 = 12 - (Math.abs(month2) % 12);
	}
	var day2 = day;
	var days2 = new Date(year2, month2, 0).getDate();
	if (day2 > days2) {
		day2 = days2;
	}
	month2 = month2.toString().padStart(2, 0)
	var t2 = year2 + '-' + month2 + '-' + day2;
	return t2;
}
/**
 *获取下几天的输入日期
 *{param:DateTime} date 输入日期(YYYY-MM-DD)
 *{param:number } num 天数
 */
export function getNextDay(date, num = 1) {
	let time = new Date(date).getTime() + num * 24 * 60 * 60 * 1000
	return format(time, 'yyyy-MM-dd')
}

/**
 *获取前几天的输入日期
 *{param:DateTime} date 输入日期(YYYY-MM-DD)
 *{param:number } num 天数
 */
export function getPreDay(date, num = 1) {
	let time = new Date(date).getTime() - num * 24 * 60 * 60 * 1000
	return format(time, 'yyyy-MM-dd')
}


//从对象数组array中获取键值key等于value的对象元素的label值
export function getValueByKey(array, key, label, value) {
	var str = ''
	for (let item of array) {
		if (item[key] == value) {
			str = item[label]
			break;
		}
	}
	if (str == '') {
		str = value
	}
	return str
}

export function getSingleValueByKey(params) {
	let {
		list = [], value = '', valueName = 'value', labelName = 'label'
	} = params
	if (list.length == 0) {
		return ''
	}
	if (value == undefined || value == null || value == '') {
		return ''
	}
	var str = ''
	for (let item of list) {
		if (item[valueName] == value) {
			str = item[labelName]
			break;
		}
	}
	if (str == '') {
		str = value
	}
	return str
}

export function getMutilValueByKey(params) {
	var that = this
	let {
		tree = [], value = '', valueName = 'value', labelName = 'label', childName = 'children', separator = '-',
		showAllLevels = true
	} = params
	if (tree.length == 0) {
		return ''
	}
	if (value == null || value == '') {
		return ''
	}
	var strList = []
	let middleList = deepClone(tree)
	let list = createListByTree(middleList)
	strList = value.map(function (item) {
		return getSingleValueByKey({
			list,
			value: item,
			valueName,
			labelName
		})
	})
	return showAllLevels ? strList.join(separator) : strList[strList.length - 1]
}

export function createListByTree(tree, childName = "children") {
	for (var i = 0; i < tree.length; i++) {
		if (tree[i][childName] != undefined) {
			var temp = tree[i][childName];
			// 删除孩子节点
			delete tree[i][childName];
			// 孩子节点加入数组末尾
			for (var j = 0; j < temp.length; j++) {
				tree.push(temp[j]);
			}
		}
	}
	return tree;
}

export function convertCurrency(money) {
	//汉字的数字
	var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
	//基本单位
	var cnIntRadice = new Array('', '拾', '佰', '仟');
	//对应整数部分扩展单位
	var cnIntUnits = new Array('', '万', '亿', '兆');
	//对应小数部分单位
	var cnDecUnits = new Array('角', '分', '毫', '厘');
	//整数金额时后面跟的字符
	var cnInteger = '整';
	//整型完以后的单位
	var cnIntLast = '元';
	//最大处理的数字
	var maxNum = 999999999999999.9999;
	//金额整数部分
	var integerNum;
	//金额小数部分
	var decimalNum;
	//输出的中文金额字符串
	var chineseStr = '';
	//分离金额后用的数组，预定义
	var parts;
	if (money == '') {
		return '';
	}
	money = parseFloat(money);
	if (money >= maxNum) {
		//超出最大处理数字
		return '';
	}
	if (money == 0) {
		chineseStr = cnNums[0] + cnIntLast + cnInteger;
		return chineseStr;
	}
	//转换为字符串
	money = money.toString();
	if (money.indexOf('.') == -1) {
		integerNum = money;
		decimalNum = '';
	} else {
		parts = money.split('.');
		integerNum = parts[0];
		decimalNum = parts[1].substr(0, 4);
	}
	//获取整型部分转换
	if (parseInt(integerNum, 10) > 0) {
		var zeroCount = 0;
		var IntLen = integerNum.length;
		for (var i = 0; i < IntLen; i++) {
			var n = integerNum.substr(i, 1);
			var p = IntLen - i - 1;
			var q = p / 4;
			var m = p % 4;
			if (n == '0') {
				zeroCount++;
			} else {
				if (zeroCount > 0) {
					chineseStr += cnNums[0];
				}
				//归零
				zeroCount = 0;
				chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
			}
			if (m == 0 && zeroCount < 4) {
				chineseStr += cnIntUnits[q];
			}
		}
		chineseStr += cnIntLast;
	}
	//小数部分
	if (decimalNum != '') {
		var decLen = decimalNum.length;
		for (var i = 0; i < decLen; i++) {
			var n = decimalNum.substr(i, 1);
			if (n != '0') {
				chineseStr += cnNums[Number(n)] + cnDecUnits[i];
			}
		}
	}
	if (chineseStr == '') {
		chineseStr += cnNums[0] + cnIntLast + cnInteger;
	} else if (decimalNum == '') {
		chineseStr += cnInteger;
	}
	return chineseStr
}
/* 数字转换为汉子 */
export function convertToChinaNum(num) {
	var arr1 = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
	var arr2 = new Array('', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿');//可继续追加更高位转换值
	if (!num || isNaN(num)) {
		return "零";
	}
	var english = num.toString().split("")
	var result = "";
	for (var i = 0; i < english.length; i++) {
		var des_i = english.length - 1 - i;//倒序排列设值
		result = arr2[i] + result;
		var arr1_index = english[des_i];
		result = arr1[arr1_index] + result;
	}
	//将【零千、零百】换成【零】 【十零】换成【十】
	result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十');
	//合并中间多个零为一个零
	result = result.replace(/零+/g, '零');
	//将【零亿】换成【亿】【零万】换成【万】
	result = result.replace(/零亿/g, '亿').replace(/零万/g, '万');
	//将【亿万】换成【亿】
	result = result.replace(/亿万/g, '亿');
	//移除末尾的零
	result = result.replace(/零+$/, '')
	//将【零一十】换成【零十】
	//result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
	//将【一十】换成【十】
	result = result.replace(/^一十/g, '十');
	return result;
};

// 判断arr是否为一个数组，返回一个bool值
export function isArray(arr) {
	return Object.prototype.toString.call(arr) === '[object Array]';
}

// 深度克隆
export function deepClone(obj) {
	// 对常见的“非”值，直接返回原来值
	if ([null, undefined, NaN, false].includes(obj)) return obj;
	if (typeof obj !== "object" && typeof obj !== 'function') {
		//原始类型直接返回
		return obj;
	}
	var o = isArray(obj) ? [] : {};
	for (let i in obj) {
		if (obj.hasOwnProperty(i)) {
			o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
		}
	}
	return o;
}

//保留2位小数，如：2，还会保留2 不会补0
export function toDecimal2NoZero(x, pointNum = 2) {
	// let num = 100;
	// if (pointNum == 2) {
	// 	num = 100
	// }
	// if (pointNum == 1) {
	// 	num == 10
	// }
	// if (pointNum == 0) {
	// 	num = 1
	// }
	let num = Math.pow(10, pointNum)
	var f = Math.round(parseFloat(x) * num) / num;
	// var s = f.toString();
	var s = f;
	return s;
}

// add by fjw in 2021.10.11: 格式化金额  num.toFixed(2);
// format: A B C D
export function formatDecimal(decimal, format) {
	decimal = parseFloat(decimal);
	switch (format) {
		case 'A': // 取整
			// console.log("小数" + decimal);
			var mode = decimal % 5; // console.log("取余" + mode);
			var value = parseInt(decimal / 5);
			if (mode > 0) value += 1;
			decimal = 5 * value;
			break;
		case 'B': // 四舍五入
			decimal = Math.round(parseFloat(decimal));
			break;
		case 'C': // 一位小数
			decimal = decimal.toFixed(1);
			break;
		case 'D': // 两位小数
			decimal = decimal.toFixed(2);
			break;
		default: break;
	}
	return decimal;
}


let timer, flag;
/**
 * 节流原理：在一定时间内，只能触发一次
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
export function throttle(func, wait = 1000, immediate = true) {
	if (immediate) {
		if (!flag) {
			flag = true;
			// 如果是立即执行，则在wait毫秒内开始时执行
			typeof func === 'function' && func();
			timer = setTimeout(() => {
				flag = false;
			}, wait);
		}
	} else {
		if (!flag) {
			flag = true
			// 如果是非立即执行，则在wait毫秒内的结束处执行
			timer = setTimeout(() => {
				flag = false
				typeof func === 'function' && func();
			}, wait);
		}
	}
};

let timeout = null;

/**
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
export function debounce(func, wait = 1000, immediate = false) {
	// 清除定时器
	if (timeout !== null) clearTimeout(timeout);
	// 立即执行，此类情况一般用不到
	if (immediate) {
		var callNow = !timeout;
		timeout = setTimeout(function () {
			timeout = null;
		}, wait);
		if (callNow) typeof func === 'function' && func();
	} else {
		// 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
		timeout = setTimeout(function () {
			typeof func === 'function' && func();
		}, wait);
	}
}


import store from "@/store"
export function hasRole(value) {
	const super_admin = "admin";
	const roles = store.getters && store.getters.roles
	if(!roles || roles.length <= 0) return false;
	
	if (value && value instanceof Array && value.length > 0) {
		const roleFlag = value
		const hasRole = roles.some(role => {
			return super_admin === role || roleFlag.includes(role);
		})
		return hasRole;
	} else {
		return false
	}
}

export function hasPost(value){
	const super_post = 'admin'
	const posts = store.getters && store.getters.posts;
	if(!posts || posts.length <= 0) return false;

	if (value && value instanceof Array && value.length > 0) {
		const roleFlag = value
		const hasPost = posts.some(post => {
			return super_post === post || roleFlag.includes(post)
		})
		return hasPost;
	}else{
		return false;
	}
}

// add by fjw in 2021.10.16
export function routerPath(menu) {
	if (menu == null || menu == undefined || menu == '') return null;
	var allRoutersPathMap = store.state.permission.allRoutersPathMap;
	return allRoutersPathMap[menu];
}

export function hasCurrentRole(value) {
	const super_admin = "admin";
	const roles = store.getters && store.getters.currentRole
	if (value && value instanceof Array && value.length > 0) {
		const roleFlag = value
		const hasRole = roles.some(role => {
			return super_admin === role || roleFlag.includes(role)
		})
		if (!hasRole) {
			return false
		}
		return true
	} else {
		return false
	}
}

export function hasPermi(value) {
	const all_permission = "*:*:*";
	const permissions = store.getters && store.getters.permissions
	if (value && value instanceof Array && value.length > 0) {
		const permissionFlag = value
		const hasPermissions = permissions.some(permission => {
			return all_permission === permission || permissionFlag.includes(permission)
		})
		if (!hasPermissions) {
			return false
		}
		return true
	} else {
		return false
	}
}

export function strDefault(str, value) {
	if (str == undefined || str == null || str == '') {
		return value
	}
	return str;
}

export function hideMobile(mobile) {
	var reg = /^(\d{3})\d{4}(\d{4})$/;
	mobile = mobile.replace(reg, "$1****$2");
	return mobile;
}
// 计算2个时间差天数
export function computingTime(startDate, endDate) {
	var date3 = endDate.getTime() - startDate.getTime();
	return Math.floor(date3 / (24 * 3600 * 1000));
}
